<?php

class Auth_Adapter implements Zend_Auth_Adapter_Interface{
	
	
	const INVALID_USERNAME = "username could not be found or was invalid";
	const INVALID_PASSWORD = "password for given username was invalid";
	
	/**
	 * @var Doctrine_Model_Users
	 */
	protected $user;
	/**
	 * @var string
	 */
	protected $username;
	/**
	 * @var string
	 */
	protected $password;
	
	public function __construct($username, $password){
		$this->username = $username;
		$this->password = $password;
	}
	
	/**
	 * @throws Zend_Auth_Adapter_Exception
	 * @returns Zend_Auth_Result
	 */
	public function authenticate(){
		
		try{
			$this->user = Doctrine_Model_Users::authenticate($this->username, $this->password);
			return $this->createResult(Zend_Auth_Result::SUCCESS);
		}catch(Exception $e){
			
			if($e->getMessage() == Doctrine_Model_Users::INVALID_USERNAME){
				return $this->createResult(Zend_Auth_Result::FAILURE_IDENTITY_NOT_FOUND, 
								array(
										self::INVALID_USERNAME
									));					
			}
			
			if($e->getMessage() == Doctrine_Model_Users::INVALID_PASSWORD){
				return $this->createResult(Zend_Auth_Result::FAILURE_CREDENTIAL_INVALID, 
								array(
										self::INVALID_PASSWORD
									));					
			}
			
		}
	}
	
	protected function createResult($code, array $message = array()){
		return new Zend_Auth_Result($code, $this->user, $message);
	}
	
}